package com.ywy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ywy.entity.UserMessage;
import com.ywy.service.UserMessageService;
import com.ywy.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * WebSocket Service实现类
 *
 * @author ywy
 * @date 2021/12/29 16:09
 */
@Slf4j
@Service
public class WebSocketServiceImpl implements WebSocketService {
    @Autowired
    private UserMessageService userMessageService;
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Async
    @Override
    public void sendMessCountToUser(Integer userId) {
        // 查询用户未读消息
        QueryWrapper<UserMessage> queryWrapper = new QueryWrapper<UserMessage>()
                .eq("to_user_id", userId)
                .eq("status", 0);
        int count = userMessageService.count(queryWrapper);
        // WebSocket通知，该方法会自动在前面添加前缀/user
        messagingTemplate.convertAndSendToUser(userId.toString(), "/messCount", count);
        log.info("ws向用户：{}发送消息，数量：{}", userId, count);
    }
}
